<template>
  <div class="default_login">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="rules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="form-layer">
        <el-form-item prop="username" class="smscode_formitem">
          <el-input
            ref="username"
            v-model="loginForm.username"
            prop="name"
            type="text"
            autocomplete="on"
            placeholder="请输入手机号码"
            @keyup.native="keyUp"
          />
        </el-form-item>
        <el-form-item
          v-if="isPwdLogin"
          prop="password"
          class="smscode_formitem"
        >
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            autocomplete="on"
            @keyup.native="keyUp"
          >
            <i
              slot="suffix"
              @click="showPwd"
              class="password_icon"
              :class="
                passwordType === 'password'
                  ? 'el-icon-turn-off'
                  : 'el-icon-open'
              "
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item v-else prop="smscode" :show-message="isShowMessage">
          <div class="smscode_formitem">
            <el-input
              ref="smscode"
              v-model="loginForm.smscode"
              prop="smscode"
              type="text"
              autocomplete="on"
              placeholder="请输入验证码"
              @keyup.native="keyUp"
            />
            <div class="smscode_text" @click="getSmscode">
              <span class="text">{{ smscodeText }}</span>
            </div>
          </div>
        </el-form-item>
        <el-button
          :loading="loading"
          class="login_btn"
          type="primary"
          size="big"
          style="width: 100%; margin-bottom: 20px"
          @click.native.prevent="handleLogin"
        >
          登录
        </el-button>
        <span class="customMsg" v-if="!isShowMessage">{{ signMsg }}</span>
        <el-checkbox style="margin-top: 20px; font-size: 12px; color: #d6d6d7">
          未注册手机登登录时会自动创建新账号，我已阅读并同意
          <span class="tk">服务协议</span> 和 <span class="tk">隐私权条款</span>
        </el-checkbox>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { ElForm, FormRules } from "element-plus";
import propmpts from "@/config";
import { isElectron } from "@/utils";
import { useRouter } from "vue-router";
export default defineComponent({
  name: "",
  props: ["isPwdLogin"],
  setup(props) {
    function validataorSmscode(_: any, value: string, callback: Function) {
      let reg = /^\d{6}$/;
      isShowMessage.value = true;
      if (value === "") {
        callback(new Error("请输入验证码"));
        return;
      }
      if (!reg.test(value)) {
        callback(new Error("验证码由六位数字组成"));
        return;
      }
      callback();
    }
    const rules: FormRules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      smscode: [
        {
          required: true,
          trigger: "blur",
          validator: validataorSmscode,
        },
      ],
    };
    let timer: any = null;
    const isShowMessage = ref(false);
    const signMsg = ref("");
    const loading = ref(false);
    const smscodeText = ref("获取验证码");
    const isLogin = ref(false);
    const passwordType = ref("password");
    const loginFormRef = ref<InstanceType<typeof ElForm>>();
    const loginForm = reactive({
      username: "",
      smscode: "",
      password: "",
    });
    const router = useRouter();
    if (props.isPwdLogin) {
      delete rules.smscode;
      rules["password"] = [
        { required: true, message: "请输入密码", trigger: "blur" },
      ];
    }
    function keyUp(e: KeyboardEvent) {
      if (e.code === "Enter") {
        handleLogin();
      }
    }
    function showPwd() {
      if (passwordType.value === "password") {
        passwordType.value = "";
      } else {
        passwordType.value = "password";
      }
    }
    async function getSmscode() {
      if (smscodeText.value === "获取验证码") {
        loginFormRef.value?.validateField("username", async (valid) => {
          if (valid) {
            let initTime = 60;
            smscodeText.value = initTime + "s";
            timer = setInterval(() => {
              initTime--;
              smscodeText.value = initTime + "s";
              if (initTime <= 0) {
                clearInterval(timer);
                smscodeText.value = "获取验证码";
              }
            }, 1000);
          }
        });
      }
    }
    // 点击登录
    async function handleLogin() {
      loginFormRef.value?.validate(async (valid) => {
        if (valid) {
          isLogin.value = true;
          loading.value = true;
          let token = "test";
          localStorage.setItem("_token_", token);
          localStorage.setItem("propmpts", JSON.stringify(propmpts));
          if (isElectron()) {
            const { ipcRenderer } = require("electron");
            await ipcRenderer.invoke("isLogin");
          } else {
            router.push("/search");
          }
        } else {
          return false;
        }
      });
    }
    return {
      isShowMessage,
      loginForm,
      isLogin,
      signMsg,
      loading,
      smscodeText,
      rules,
      getSmscode,
      handleLogin,
      keyUp,
      loginFormRef,
      passwordType,
      showPwd,
    };
  },
});
</script>
<style scoped lang="scss">
.form-layer {
  .login_btn {
    height: 40px;
    margin-top: 20px;
    background-color: #8080ff;
  }

  .smscode_formitem {
    position: relative;
    width: 100%;
    .smscode_text {
      position: absolute;
      top: 50%;
      right: 20px;
      padding: 0 10px;
      border: 1px solid #99c5ec;
      color: #8fc2ee;
      box-sizing: border-box;
      border-radius: 4px;
      font-size: 12px;
      cursor: pointer;
      transform: translateY(-50%);
    }
  }
}
.tk {
  color: #8080ff;
}
</style>
<style lang="scss">
.form-layer {
  .login_btn {
    .el-button:focus,
    .el-button:hover {
      background-color: #8080ff;
      border-color: #8080ff;
    }
    .el-button:focus-visible {
      outline: 2px solid #8080ff;
      outline-offset: 1px;
    }
  }
  .el-checkbox {
    white-space: wrap;
  }
  .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #8080ff;
  }
  .smscode_formitem {
    .el-input__wrapper {
      height: 40px;
    }
    .el-form-item.is-error .el-input__wrapper,
    .el-input__wrapper:hover,
    .el-input__wrapper,
    .el-input__wrapper.is-focus {
      box-shadow: none;
      background-color: #f7f7f7;
    }
  }
}
</style>
